<template>
  <el-button class="send-code-btn" :disabled="isSending || countdown > 0" @click="sendCode">
    <text class="sent-code-text">{{ countdown > 0 ? `${countdown}秒后重试` : "获取验证码" }}</text>
  </el-button>
</template>
<script setup>
import CommonAPI from "@/api/system/common";
const isSending = ref(false); // 是否正在发送验证码
const countdown = ref(0); // 验证码倒计时
const emit = defineEmits(["getCode"]);
const props = defineProps({
  mobile: {
    type: String,
    default: "",
  },
  smsType: {
    type: String,
    default: "",
  },
  validateFunction: {
    type: Function,
    default: () => {},
  },
});
// 发送验证码
const sendCode = async () => {
  const result = await props.validateFunction();
  if (!result) {
    return;
  }
  try {
    isSending.value = true;
    countdown.value = 60; // 设置倒计时为60秒
    const data = await CommonAPI.captchaSmse({ mobile: props.mobile, smsType: props.smsType });
    emit("getCode", data.data);
    ElMessage.success("验证码已发送，请注意查收");
    const interval = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(interval);
        isSending.value = false;
      }
    }, 1000);
  } catch (error) {
    isSending.value = false;
    countdown.value = 0;
  }
};

const setCode = () => {
  isSending.value = false;
  countdown.value = 0;
};
defineExpose({
  setCode,
});
</script>
<style scoped lang="scss">
.sent-code-text {
  color: #1b4fff;
}
</style>
